const util = require('util')
const axios = require('axios');
const {sequelize} = require('../../core/db')
const {Sequelize, Model, Op} = require('sequelize');
const {
    Favor
} = require('./favor')


class Book extends Model{
    async detail(ids) {
       const url = util.format(global.config.yushu.detailUrl, ids);
       const detail = await axios.get(url);
       return detail;
    }
    
    static async searchFromYuShu (q, count, start, summary = 1) {
        const url = util.format(global.config.yushu.keywordUrl, encodeURI(q), count, start, summary);
        const result  = await axios.get(url);
        return result.data;
    }

    // 获取我喜欢书籍的数量
    static async getMyFavorBookCount(uid) {
       const count = await Favor.count({
           where: {
               type: 400,
               uid
           }
       });
       return count;
    }

    // 获取某个书籍的点赞数以及我的点赞状态
    static async getBookFavor(uid, bookId) {
        const count = await Favor.count({
            where: {
                art_id: bookId,
                type: 400
            }
        })
        
        const favor = await Favor.findOne({
            where: {
                art_id: bookId,
                uid,
                type: 400
            }
        });
        
        return {
            fav_nums: count,
            like_status: favor ? 1 : 0
        }
    }

} 

Book.init({
    id: {
        type: Sequelize.INTEGER,
        primaryKey: true
    },
    fav_nums: {
        type: Sequelize.INTEGER,
        defaultValue: 0
    }
}, {
    sequelize,
    tableName: 'book'
})

module.exports = {
    Book
}